#!/usr/bin/env bash
#
# Helper to run the MWRI radiance diagnostics and NAM analysis sampling
# without manually re-entering the environment export sequence each time.
# The script assumes it is invoked from the repository root.

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
eccodes_overlay="${repo_root}/deps/eccodes_overrides"
cris_bufr="/home/docker/GSI/comGSIv3.7_EnKFv1.3-mwri/test/satellite_gdas/gdas.t00z.crisf4.tm00.bufr_d"
prepbufr_file="/home/docker/GSI/comGSIv3.7_EnKFv1.3-mwri/test/satellite_gdas/gdas.t00z.prepbufr.nr"
bufr_table="/home/docker/GSI/comGSIv3.7_EnKFv1.3-mwri/fix/prepobs_prep.bufrtable"
output_dir="${repo_root}/results/mwri_regional_case_nam_geofix"
stats_json="${repo_root}/results/mwri_regional_case_diag_rads/cris_stats_latest.json"
scenario="mwri"

export JULIA_NUM_THREADS=1
export OPENBLAS_NUM_THREADS=1

if [[ ! -d "${eccodes_overlay}" ]]; then
    echo "ERROR: expected overlay directory at ${eccodes_overlay}" >&2
    exit 2
fi

export ECCODES_DEFINITION_PATH="${eccodes_overlay}:${ECCODES_DEFINITION_PATH:-}"

mkdir -p "$(dirname "${stats_json}")" "${output_dir}"

cmd_capture_stats=(
    julia --project="${repo_root}" --
    "${repo_root}/scripts/julia/capture_radiance_stats.jl"
    "${cris_bufr}"
    "${stats_json}"
    1000
)

cmd_run_nam=(
    julia --project="${repo_root}" --
    "${repo_root}/scripts/julia/run_mwri_regional_case.jl"
    "--scenario=${scenario}"
    --analysis-mode=nam
    --radiance-sample=50
    --prepbufr="${prepbufr_file}"
    --bufr-table="${bufr_table}"
    --output="${output_dir}"
)

printf 'Running radiance stats: %s\n' "${cmd_capture_stats[*]}"
"${cmd_capture_stats[@]}"

printf 'Running NAM radiance sample: %s\n' "${cmd_run_nam[*]}"
"${cmd_run_nam[@]}"
